<template>
  <div class="student-exam-records-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>学生考试记录</span>
          <el-button type="primary" @click="fetchRecords">
            刷新
          </el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :inline="true" :model="queryForm" class="search-form" label-width="80px">
        <el-form-item label="试卷">
          <el-select
            v-model="queryForm.paperId"
            placeholder="请选择试卷"
            clearable
            filterable
            style="width: 200px"
            @change="handleQuery"
          >
            <el-option
              v-for="paper in paperOptions"
              :key="paper.id"
              :label="paper.name"
              :value="paper.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="学生">
          <el-select
            v-model="queryForm.studentId"
            placeholder="请选择学生"
            clearable
            filterable
            style="width: 200px"
            @change="handleQuery"
          >
            <el-option
              v-for="student in studentOptions"
              :key="student.id"
              :label="`${student.realName}（${student.username}）`"
              :value="student.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-space>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-space>
        </el-form-item>
      </el-form>

      <el-table
        v-loading="loading"
        :data="recordList"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="paperName" label="试卷名称" min-width="200" />
        <el-table-column prop="studentName" label="学生姓名" width="120" />
        <el-table-column prop="studentUsername" label="学号" width="120" />
        <el-table-column label="开始时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.startTime) }}
          </template>
        </el-table-column>
        <el-table-column label="结束时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.endTime) }}
          </template>
        </el-table-column>
        <el-table-column label="总分" width="100">
          <template #default="{ row }">
            <span v-if="row.totalScore !== null && row.totalScore !== undefined" :class="getScoreClass(row.totalScore)">
              {{ row.totalScore.toFixed(2) }} 分
            </span>
            <span v-else style="color: #909399">未评分</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleViewDetail(row.examId)"
            >
              查看答题详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 答题详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      title="答题详情"
      width="80%"
      :close-on-click-modal="false"
    >
      <div v-if="examDetail" class="exam-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="学生姓名">{{ examDetail.studentName }}</el-descriptions-item>
          <el-descriptions-item label="学号">{{ examDetail.studentUsername }}</el-descriptions-item>
          <el-descriptions-item label="试卷名称">{{ examDetail.paperName }}</el-descriptions-item>
          <el-descriptions-item label="总分">
            <span :class="getScoreClass(examDetail.totalScore)">
              {{ examDetail.totalScore }} 分
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="开始时间">{{ formatDateTime(examDetail.startTime) }}</el-descriptions-item>
          <el-descriptions-item label="结束时间">{{ formatDateTime(examDetail.endTime) }}</el-descriptions-item>
        </el-descriptions>

        <el-divider>答题详情</el-divider>

        <div
          v-for="(question, index) in examDetail.questions"
          :key="question.questionId"
          class="question-result-item"
        >
          <div class="question-header">
            <span class="question-number">第 {{ index + 1 }} 题</span>
            <span class="question-type">{{ getQuestionTypeLabel(question.type) }}</span>
            <span class="question-score">
              得分：<span :class="getQuestionScoreClass(question.score)">{{ question.score }} 分</span>
            </span>
          </div>

          <div class="question-content">
            <div class="question-text">{{ question.content }}</div>

            <!-- 选择题显示选项 -->
            <div v-if="question.options" class="question-options">
              <div
                v-for="(option, key) in question.options"
                :key="key"
                class="option-item"
                :class="getOptionClass(question, key)"
              >
                {{ key }}. {{ option }}
                <span v-if="isCorrectOption(question, key)" class="correct-mark">✓</span>
                <span v-if="isSelectedOption(question, key)" class="selected-mark">学生选择</span>
              </div>
            </div>

            <!-- 答案显示 -->
            <div class="answer-section">
              <div class="answer-row">
                <span class="answer-label">正确答案：</span>
                <span class="correct-answer">{{ question.correctAnswer }}</span>
              </div>
              <div class="answer-row">
                <span class="answer-label">学生答案：</span>
                <span class="student-answer" :class="getAnswerClass(question)">
                  {{ question.studentAnswer || '未作答' }}
                </span>
              </div>
              <div class="answer-row">
                <span class="answer-label">得分：</span>
                <span class="score-text">{{ question.score }} 分</span>
              </div>
            </div>

            <!-- 解析 -->
            <div v-if="question.analysis" class="analysis-section">
              <div class="analysis-title">解析：</div>
              <div class="analysis-content">{{ question.analysis }}</div>
            </div>

            <!-- 教师评语 -->
            <div v-if="question.teacherComment" class="comment-section">
              <div class="comment-title">教师评语：</div>
              <div class="comment-content">{{ question.teacherComment }}</div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { getAllExamRecords, getExamDetail, type ExamRecord, type ExamDetail } from '../../api/exam'
import { getPaperList, type PaperInfo } from '../../api/paper'
import { getUserList, type UserInfo } from '../../api/user'
import { useUserStore } from '../../store/user'

const userStore = useUserStore()
const loading = ref(false)
const allRecords = ref<ExamRecord[]>([])
const paperOptions = ref<PaperInfo[]>([])
const studentOptions = ref<UserInfo[]>([])
const showDetailDialog = ref(false)
const examDetail = ref<ExamDetail | null>(null)

const queryForm = reactive({
  paperId: null as number | null,
  studentId: null as number | null
})

const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 过滤后的记录列表
const filteredRecords = computed(() => {
  let filtered = allRecords.value

  if (queryForm.paperId) {
    filtered = filtered.filter(r => r.paperId === queryForm.paperId)
  }

  if (queryForm.studentId) {
    filtered = filtered.filter(r => r.studentId === queryForm.studentId)
  }

  return filtered
})

// 分页后的记录列表
const recordList = computed(() => {
  const start = (pagination.page - 1) * pagination.size
  const end = start + pagination.size
  return filteredRecords.value.slice(start, end)
})

// 获取考试记录
const fetchRecords = async () => {
  loading.value = true
  try {
    const res = await getAllExamRecords()
    allRecords.value = res.data || []
    pagination.total = filteredRecords.value.length
  } catch (error: any) {
    ElMessage.error(error.message || '获取考试记录失败')
  } finally {
    loading.value = false
  }
}

// 获取试卷列表
const fetchPaperList = async () => {
  try {
    const res = await getPaperList({
      page: 1,
      size: 1000,
      teacherId: userStore.isAdmin ? undefined : (userStore.userId ? parseInt(userStore.userId) : undefined)
    })
    paperOptions.value = res.data.data || []
  } catch (error) {
    ElMessage.error('获取试卷列表失败')
  }
}

// 获取学生列表
const fetchStudentList = async () => {
  try {
    const res = await getUserList({
      roleType: 'STUDENT',
      page: 1,
      size: 1000
    })
    studentOptions.value = res.data.data || []
  } catch (error) {
    ElMessage.error('获取学生列表失败')
  }
}

// 查看详情
const handleViewDetail = async (examId: number) => {
  try {
    const res = await getExamDetail(examId)
    examDetail.value = res.data
    showDetailDialog.value = true
  } catch (error: any) {
    ElMessage.error(error.message || '获取考试详情失败')
  }
}

// 查询
const handleQuery = () => {
  pagination.page = 1
  pagination.total = filteredRecords.value.length
}

// 重置
const handleReset = () => {
  queryForm.paperId = null
  queryForm.studentId = null
  handleQuery()
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.page = 1
}

// 当前页变化
const handlePageChange = (page: number) => {
  pagination.page = page
}

// 格式化日期时间
const formatDateTime = (dateTimeStr: string) => {
  if (!dateTimeStr) return ''
  const date = new Date(dateTimeStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取题目类型标签
const getQuestionTypeLabel = (type: string) => {
  const typeMap: Record<string, string> = {
    single: '单选题',
    multiple: '多选题',
    judge: '判断题',
    fill: '填空题',
    essay: '简答题'
  }
  return typeMap[type] || type
}

// 获取得分样式类
const getScoreClass = (score: number) => {
  if (score >= 90) return 'score-excellent'
  if (score >= 60) return 'score-pass'
  return 'score-fail'
}

// 获取得分样式类（题目）
const getQuestionScoreClass = (score: number) => {
  if (score > 0) return 'score-correct'
  return 'score-wrong'
}

// 获取答案样式类
const getAnswerClass = (question: any) => {
  const studentAnswer = question.studentAnswer || ''
  const correctAnswer = question.correctAnswer || ''

  if (question.type === 'multiple') {
    const studentAnswers = studentAnswer.split(',').sort().join(',')
    const correctAnswers = correctAnswer.split(',').sort().join(',')
    return studentAnswers === correctAnswers ? 'answer-correct' : 'answer-wrong'
  }

  return studentAnswer.toLowerCase() === correctAnswer.toLowerCase() ? 'answer-correct' : 'answer-wrong'
}

// 判断是否为正确答案选项
const isCorrectOption = (question: any, key: string): boolean => {
  const correctAnswer = question.correctAnswer || ''
  if (question.type === 'multiple') {
    return correctAnswer.split(',').includes(key)
  }
  return correctAnswer === key
}

// 判断是否为选中的选项
const isSelectedOption = (question: any, key: string): boolean => {
  const studentAnswer = question.studentAnswer || ''
  if (question.type === 'multiple') {
    return studentAnswer.split(',').includes(key)
  }
  return studentAnswer === key
}

// 获取选项样式类
const getOptionClass = (question: any, key: string): string => {
  const isCorrect = isCorrectOption(question, key)
  const isSelected = isSelectedOption(question, key)

  if (isCorrect && isSelected) {
    return 'option-correct'
  } else if (isCorrect && !isSelected) {
    return 'option-missed'
  } else if (!isCorrect && isSelected) {
    return 'option-wrong'
  }
  return ''
}

onMounted(() => {
  fetchPaperList()
  fetchStudentList()
  fetchRecords()
})

// 监听过滤后的记录变化，更新分页总数
watch(filteredRecords, () => {
  pagination.total = filteredRecords.value.length
  if (pagination.page > 1 && filteredRecords.value.length === 0) {
    pagination.page = 1
  }
})
</script>

<style scoped>
.student-exam-records-container {
  padding: 20px;
  overflow: visible;
}

.student-exam-records-container :deep(.el-card) {
  overflow: visible;
}

.student-exam-records-container :deep(.el-card__body) {
  overflow: visible;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.score-excellent {
  color: #67c23a;
  font-weight: bold;
}

.score-pass {
  color: #409eff;
  font-weight: bold;
}

.score-fail {
  color: #f56c6c;
  font-weight: bold;
}

.question-result-item {
  margin-bottom: 30px;
  padding: 20px;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.question-header {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e4e7ed;
}

.question-number {
  font-weight: bold;
  font-size: 16px;
}

.question-type {
  color: #409eff;
}

.question-score {
  margin-left: auto;
}

.score-correct {
  color: #67c23a;
  font-weight: bold;
}

.score-wrong {
  color: #f56c6c;
}

.question-content {
  padding-left: 20px;
}

.question-text {
  font-size: 15px;
  line-height: 1.6;
  margin-bottom: 15px;
}

.question-options {
  margin: 15px 0;
}

.option-item {
  padding: 10px;
  margin-bottom: 8px;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
  position: relative;
}

.option-correct {
  background-color: #f0f9ff;
  border-color: #67c23a;
  color: #67c23a;
}

.option-wrong {
  background-color: #fef0f0;
  border-color: #f56c6c;
  color: #f56c6c;
}

.option-missed {
  background-color: #fff7e6;
  border-color: #e6a23c;
  color: #e6a23c;
}

.correct-mark {
  margin-left: 10px;
  color: #67c23a;
  font-weight: bold;
}

.selected-mark {
  margin-left: 10px;
  font-size: 12px;
  color: #409eff;
}

.answer-section {
  margin: 20px 0;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.answer-row {
  margin-bottom: 10px;
}

.answer-row:last-child {
  margin-bottom: 0;
}

.answer-label {
  font-weight: bold;
  margin-right: 10px;
}

.correct-answer {
  color: #67c23a;
  font-weight: bold;
}

.student-answer {
  font-weight: bold;
}

.answer-correct {
  color: #67c23a;
}

.answer-wrong {
  color: #f56c6c;
}

.score-text {
  color: #409eff;
  font-weight: bold;
}

.analysis-section {
  margin-top: 15px;
  padding: 15px;
  background-color: #f0f9ff;
  border-radius: 4px;
}

.analysis-title {
  font-weight: bold;
  margin-bottom: 8px;
  color: #409eff;
}

.analysis-content {
  line-height: 1.6;
  color: #606266;
}

.comment-section {
  margin-top: 15px;
  padding: 15px;
  background-color: #fff7e6;
  border-radius: 4px;
}

.comment-title {
  font-weight: bold;
  margin-bottom: 8px;
  color: #e6a23c;
}

.comment-content {
  line-height: 1.6;
  color: #606266;
}

.exam-detail {
  max-height: 70vh;
  overflow-y: auto;
}
</style>

